package com.example.studentmanagement2.service.Impl;

import com.example.studentmanagement2.exception.StudentNotFoundException;
import com.example.studentmanagement2.model.User;
import com.example.studentmanagement2.repository.Repository.UserRepository;
import com.example.studentmanagement2.service.UserService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

@Service
@Transactional
public class UserServiceImpl implements UserService {

    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder; // 添加密码编码器

    public UserServiceImpl(
            UserRepository userRepository,
            PasswordEncoder passwordEncoder // 注入PasswordEncoder
    ) {
        this.userRepository = userRepository;
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    public List<User> getAllUsers() {
        return userRepository.findAll();
    }

    @Override
    public Optional<User> getUserById(String id) {
        return Optional.ofNullable(userRepository.findById(id)
                .orElseThrow(() -> new StudentNotFoundException("User not found with id: " + id)));
    }

    @Override
    public User addUser(User user) {
        if (userRepository.existsById(user.getId())) {
            throw new IllegalArgumentException("学号已存在！");
        }

        // 加密存储密码
        String encodedPassword = passwordEncoder.encode(user.getPassword());
        user.setPassword(encodedPassword);

        return userRepository.save(user);
    }


    // UserServiceImpl.java
    @Override
    @Transactional
    public User updateUser(String originalId, User user) {
        User existingUser = userRepository.findById(originalId)
                .orElseThrow(() -> new StudentNotFoundException("原始学号不存在"));

        // 检查是否需要更新密码
        if (user.getPassword() != null && !user.getPassword().isEmpty()) {
            // 加密新密码
            String encodedPassword = passwordEncoder.encode(user.getPassword());
            user.setPassword(encodedPassword);
        } else {
            // 保留原密码
            user.setPassword(existingUser.getPassword());
        }

        userRepository.update(user, originalId);
        return user;
    }

    @Override
    public List<User> searchUsers(String keyword) {
        return userRepository.search(keyword);
    }



    @Override
    public void deleteUser(String id) {
        userRepository.deleteById(id);
    }


}
